package com.example.servletdemo.servlet;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.concurrent.Executor;

@WebServlet(urlPatterns = "/AsyncServlet",asyncSupported = true)
public class AsyncServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");

        PrintWriter out = resp.getWriter();
        out.print("<h2>hello AsyncServlet</h2>");

        // 异步执行，new Thread传递AsyncContext对象并且start
        AsyncContext context = req.startAsync();
        new Thread(new ThreadTest(context)).start();

        System.out.println("AsyncServlet 执行结束："+new Date());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    //内部类实现线程
    public class ThreadTest implements Runnable{
        private AsyncContext context;

        public ThreadTest(AsyncContext context) {
            this.context=context;
        }

        @Override
        public void run() {
            //执行相关复杂业务
            ServletRequest request = context.getRequest();
            context.getResponse();
            ServletResponse response = context.getResponse();
            PrintWriter out = null;
            try {
                request.getRequestDispatcher("/index.jsp").forward(request,response);
//                out = response.getWriter();
//                out.flush();
                System.out.println("AsyncServlet=>ThreadTest 执行完成:"+new Date());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ServletException e) {
                e.printStackTrace();
            }
        }
    }
}
